#pragma once
#include<iostream>
#include<algorithm>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>

class Util{
  public:
    static inline int ReadLine(int sock, std::string& out) {
       char op = 'x'; 
       while (op != '\n') {
            size_t s = recv(sock, (void*)&op, 1, 0);
            if (s > 0) {
              if (op == '\r') {
                  //往后窥探数据 
                  recv(sock, (void*)&op, 1 ,MSG_PEEK);
                  if (op == '\n') { /*当前行已经结束了*/
                      recv(sock, (void*)&op, 1, 0);/*读取过来*/
                  }
                  else { /*普通数据,说明以'\r'为结尾*/
                      op = '\n';
                  }
              }
              //1.普通字符
              //2.'\n'
              out.push_back(op);
            }
            else if (s == 0) {//写端关闭
               close(sock); 
               return 0;
            }
            else {
               return -1;
            }
       }
       return static_cast<int>(out.size());
    }
    static inline bool CutStrToPart(const std::string& target, std::string& out1, std::string& out2, const std::string& seg) {
          auto pos = target.find(seg);
          out1 = target.substr(0, pos);
          out2 = target.substr(pos + seg.size());/*默认到结尾停止*/
          return true;
    }
    static inline void Tranform(std::string& str) {
          std::transform(str.begin(), str.end(), str.begin(), toupper);
    }
    static inline std::string Code2Desc(const int& code) {
          std::string Desc;
          switch (code) {
              case 404: 
                   Desc = "NOT_FOUND";
                   break;
              case 400:
                   Desc = "BAD_REQUEST";
                   break;
              case 500:
                   Desc = "Internal_Server_Error";
                   break;
              default:
                   Desc = "OK";
                   break;
          }
          return Desc;
    }
};
